#!/usr/bin/python

import pygtk
pygtk.require('2.0')

import gtk
import gtk.glade
import gnome.ui
import gobject
import pickle
import pynotify
import subprocess
import os


class RAPIsms:
	prefs="rapisms.settings"
	icon="phone.jpg"
	iconuri="file://"+os.path.dirname(os.path.realpath(__file__))+os.path.sep+icon
	phoneNumbers=[]
	
	def load_settings(self):
		try:
			settings=pickle.load(open(self.prefs))
			(x,y,w,h,self.phoneNumbers)=settings
			for m in self.phoneNumbers:
				self.combo.prepend_text(m)
			self.window1.move(x,y)
			self.window1.resize(w,h)
		except Exception as e:
			print "Can't open settings: ",e

	def save_settings(self):
		(x,y) = self.window1.get_position()
		(w,h) = self.window1.get_size()
		model = self.combo.get_model()
		self.phoneNumbers=[]
		for m in model:
			self.phoneNumbers.append(m[0])
		settings=[x,y,w,h,self.phoneNumbers]
		pickle.dump(settings, open(self.prefs, "w"))

	def on_button1_clicked(self,obj):
		phoneNumber=self.combo.get_active_text()
		model = self.combo.get_model()
		already_in_list=False
		for m in model:
			if phoneNumber==m[0]:
				already_in_list=True
		if not already_in_list:
			self.combo.prepend_text(phoneNumber)
		i=phoneNumber.find(" ")
		if i>-1:
			phoneNumber=phoneNumber[0:phoneNumber.find(" ")]
		smsText=self.textview.get_buffer().get_text(*self.textview.get_buffer().get_bounds())
		smsText=smsText.replace("\n"," ")
		pynotify.init("RapiSMS")
		try:
			p=subprocess.Popen(["rapi","sms",phoneNumber,smsText], stderr=subprocess.PIPE)
			p.wait()
			errtext=p.stderr.readline()
			if p.returncode==0:
				notification=pynotify.Notification("RapiSMS","SMS to "+phoneNumber+" sent.",self.iconuri)
			else:
				notification=pynotify.Notification("RapiSMS","Error: "+errtext,"dialog-error")
			notification.show()
		except Exception as e:
			print e
			notification=pynotify.Notification("RapiSMS","Error: "+str(e),"dialog-error") #e.__str__()
			notification.show()

	def on_button2_clicked(self,obj):
		print obj
		# TODO: edit phone numbers
	def update_status(self,obj,data):
		print "changed"
		smsText=self.textview.get_buffer().get_text(*self.textview.get_buffer().get_bounds())
		self.status.push(0,"used "+str(len(smsText))+" chars")
	def on_window1_destroy(self,obj):
		self.save_settings()
		gtk.main_quit()

	def __init__(self):
		self.widgetTree = gtk.glade.XML("rapisms.glade")
		self.widgetTree.signal_autoconnect(self)
		self.window1=self.widgetTree.get_widget("window1")
		self.combo=self.widgetTree.get_widget("comboboxentry1")
		self.textview=self.widgetTree.get_widget("textview1")
		self.status=self.widgetTree.get_widget("statusbar1")
		store=gtk.ListStore(gobject.TYPE_STRING)
		self.combo.set_model(store)
		self.combo.set_text_column(0)	
		self.load_settings()
		self.window1.set_title("RapiSMS")
		self.window1.set_icon_from_file(self.icon)
		self.window1.show()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	sms=RAPIsms().main()

